<?php

class formEngine {

    protected $page;
    protected $tag;
    protected $formPage;
    protected $formName = 'formDefault';
    protected $resultPage;
    protected $resultApplication;
    protected $resultMessage = 'Het formulier is opgeslagen'; # This one is only displayed when the form is cleared and saved at the same time
    protected $errorType = 'alert';
    private $currentSubApp;

    protected $values = array();
    public $componentList = array();

    public function beforeInit($page, $tag, $settings = array()) {
        $this->formPage = new templateEngine('defaultform');
        $this->page = $page;
        $this->tag = $tag;
    }

    public function init() {

        # Start handling the form
        $page = $this->handleForm($this->page);

        return $page;

    }

    private function handleForm($page) {

        //$this->beforeLoad();
        $this->load($page);

        # Check if we are loading of saving the form
        if(isset($_GET['action']) && $_GET['action'] == 'save') {

            $values = $this->getPostedValues();
            $validateResponse = $this->validate($values);

            # Only when validation is true save the form
            if($validateResponse === true) {

                $saveResponse = $this->save($values);

                if($saveResponse === true) {

                    switch(strtolower($this->resultAction)){
                        case 'function':
                            $response = array('type' => 'function' , 'functionName' => $this->resultFunction, 'parameters' => $this->resultParameters);
                            break;
                        case 'resultpage':

                            if($this->resultApplication != null){
                                    $application = 'application='.$this->resultApplication.'&';
                            }

                            $response = array('type' => 'goto' , 'location' => 'index.php?'.$application.'page='.$this->resultPage);
                            break;
                        case 'externalresultpage':
                            $response = array('type' => 'goto' , 'location' => $this->resultPage);
                            break;
                        case 'refresh':
                            $response = array('type' => 'clear', 'message' => $this->resultMessage);
                            break;
                        case 'closeformwindow':
                            
                            if($this->resultApplication != null){
                                    $application = 'application='.$this->resultApplication.'&';
                            }

                            $response = array('type' => 'closeFormWindow', 'location' => 'index.php?'.$application.'page='.$this->resultPage);
                            
                            break;
                    }

                }

            } else {
                $response = array('type' => 'error' ,'message' => $validateResponse, 'errorType' => $this->errorType);
            }

            # Return the output to the browser
            echo json_encode($response);

            exit;
        }

        $page = $this->generate($page);

        return $page;

    }

    protected function beforeLoad() {

    }

    protected function load($page) {

//        # If we have some values stored in the object from a previous action, use them instead of the default field values
//        if(isset($this->values) && count($this->values) > 0){
//            foreach($this->values as $componentName => $componentValue) {
//                $component = applicationEngine::findObject($componentName);
//
//                if(is_object($component)){
//                    $component->value = $componentValue;
//                }
//            }
//        }

    }

    protected function validate($values) {
        # Dummy function to be overruled
    }

    protected function save($values){
        # Dummy function to be overruled
    }

    protected function beforeGenerate($page){

    }

    protected function generate($page) {

        $this->formPage->assign('<form id="form" action="?application='.$this->currentSubApp.'&form='.$this->formName.'&action=save">','formStart');
        $this->formPage->assign('</form>','formEnd');

        $formPage = $this->formPage->generateTemplate(true);

        $page->append($formPage, $this->tag);

        return $page;

    }

    /*
     * @author Frank Roffel
     * @version 1.0
     * @description Add an component to the form
     *
     */
    protected function addComponent($component, $settings = array()) {

        if($settings['name']){
            $componentName = $settings['name'];
        }

        # Try to find the component
        applicationEngine::loadObject($component, $componentName, $this->formPage, 'formContent', $settings);

        $this->componentList[] = $componentName;

    }

    /*
     * @author Frank Roffel
     * @version 1.0
     * @description Try to access the posted values
     *
     */
    private function getPostedValues() {

        $values = array();
        foreach($this->componentList as $key => $componentName) {

            if(isset($_GET[$componentName])) {
                $this->values[$componentName] = $_GET[$componentName];
            }
        }

        return $this->values;

    }

    public function __destruct() {

        # We keep this form in the session after use
        $_SESSION[$this->formName] = serialize($this);

    }

}


?>
